const router = require('express').Router()
const {query} = require('../../db')

router.post('/wxpay', async (req, res)=>{
    // 接收数据 （ XML ）
    if(req.body.xml.result_code[0] === 'SUCCESS' && req.body.xml.return_code[0] === 'SUCCESS') {

        let order_sn = req.body.xml.out_trade_no[0]

        let orderInfo = await query('SELECT pay_status,money,user_id FROM orders WHERE order_sn=?', order_sn)
        if(orderInfo === undefined || orderInfo.length === 0){
            res.end('<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>')
            return
        }

        if(orderInfo[0].pay_status === 0) {
            await query('UPDATE orders SET pay_status=1 WHERE order_sn=?', order_sn)
            await query('UPDATE users SET money=money+? WHERE id=?', [orderInfo[0].money, orderInfo[0].user_id])
        }
        res.end('<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>')

    }
    
})

module.exports = router